package com.weixin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weixin.config.WeiXinProperties;
import com.weixin.entity.Department;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjd
 * @Title:
 * @Description: 标签
 * @date 2021/4/13 11:40
 */
@Api("企业微信通讯录-标签管理")
@RestController
@RequestMapping("/v1.0/wei-xin/cgi-bin/tag")
public class TagContrlloer {

    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private ObjectMapper objectMapper;

    @ApiOperation("创建标签")
    @PostMapping("/create")
    public ResponseEntity createUser(@RequestParam("name") String name, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("tagname",name);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/create?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> readValue = objectMapper.readValue(result, HashMap.class);
        return resultMap(readValue,0,"tagid");
    }

    @ApiOperation("更新标签")
    @PutMapping("/update")
    public ResponseEntity updateUser(@RequestParam("name") String name,
                                     @RequestParam("id") String id, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("tagname",name);
        map.put("tagid",id);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/update?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> readValue = objectMapper.readValue(result, HashMap.class);
        return resultMap(readValue,0,"errmsg");
    }

    @ApiOperation("获取标签列表")
    @GetMapping()
    public ResponseEntity list( HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/list?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        return resultMap(map,0,"taglist");
    }


    @ApiOperation("根据id删除标签")
    @DeleteMapping("/{id}")
    public ResponseEntity deleteByUserId(@PathVariable("id") String id, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/delete?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&tagid="+id);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        return resultMap(map,0,"errmsg");

    }

    @ApiOperation("根据id获取标签成员")
    @GetMapping("/{id}")
    public ResponseEntity findByIdList(@PathVariable("id") String id, HttpSession session) throws IOException {
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/get?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        urlBuilder.append("&tagid="+id);
        String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
        Map<String, Object> map = objectMapper.readValue(result, HashMap.class);
        return resultMap(map,1,null);
    }

    @ApiOperation("增加标签成员")
    @PutMapping("{id}/addTagUsers")
    public ResponseEntity addTagUsers(@RequestParam("userList") List<String> userList,
                                      @RequestParam("partyList") List<String> partyList,
                                      @PathVariable("id") String id, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("userlist",userList);
        map.put("partylist",partyList);
        map.put("tagid",id);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/addtagusers?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> readValue = objectMapper.readValue(result, HashMap.class);
        return resultMap(readValue,1,null);
    }

    @ApiOperation("删除标签成员")
    @DeleteMapping("{id}/delTagUsers")
    public ResponseEntity delTagUsers(@RequestParam("userList") List<String> userList,
                                      @RequestParam("partyList") List<String> partyList,
                                      @PathVariable("id") String id, HttpSession session) throws IOException {
        Map  map= new HashMap<String, Object>();
        map.put("userlist",userList);
        map.put("partylist",partyList);
        map.put("tagid",id);
        String jsonStr = objectMapper.writeValueAsString(map);
        StringBuilder urlBuilder=new StringBuilder(WeiXinProperties.getUrl());
        urlBuilder.append("cgi-bin/tag/deltagusers?");
        String access_token =(String) session.getAttribute("access_token_addressBook");
        urlBuilder.append("access_token="+access_token);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求类型
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        // 封装参数和头信息
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonStr, httpHeaders);
        String result = restTemplate.postForObject(urlBuilder.toString(),httpEntity, String.class);
        Map<String, Object> readValue = objectMapper.readValue(result, HashMap.class);
        return resultMap(readValue,1,null);
    }

    private ResponseEntity resultMap(Map<String, Object> resultMap, Integer type,String key){
        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            if (entry.getKey().equals("errcode")){
                Integer integer = (Integer) resultMap.get("errcode");
                if (integer==0){
                    ResponseEntity responseEntity = type==0 ? new ResponseEntity(resultMap.get(key), HttpStatus.OK): new ResponseEntity(resultMap, HttpStatus.OK);
                    return responseEntity;
                }
            }
        }
        return new ResponseEntity(resultMap,HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
